/* $RCSFile: EntitiesODS.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/CRMWrapper3/EntitiesODS.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:32  christian.surieux
 *   Added Log to All cs files
 */

// =======================================================================
//  File: EntityODS.cs
// =======================================================================
//  This file is part of Addon Nice product.
//  Copyright (C) Addon Nice.  All rights reserved.
// =======================================================================

using System;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using CrmSdk;
using AddonNice.CRMWrapper;

namespace AddonNice.CRMWrapper
{
	public class EntitiesODS
	{

        private bool _isAdmin =	false;
		protected bool isAdmin
		{
			get
			{
				return _isAdmin;
			}
		}

		private CRMWrapperBase _wrapper = null;
		protected CRMWrapperBase wrapper
		{
			get
			{
				return _wrapper;
			}
		}


		EntityInternalItems  _entityFlags	=	EntityInternalItems.All;
		public EntityInternalItems entityFlags
		{
			get
			{
				return _entityFlags;
			}
		}

		AttributeInternalRequiredLevel _requiredLevel = AttributeInternalRequiredLevel.None | AttributeInternalRequiredLevel.ReadOnly 
            | AttributeInternalRequiredLevel.Recommended | AttributeInternalRequiredLevel.Required | AttributeInternalRequiredLevel.SystemRequired;
		public AttributeInternalRequiredLevel requiredLevel
		{
			get
			{
				return _requiredLevel;
			}
		}
			
        DataSet EntitiesDs		=	EntityConfig.CreateDataSet();

		public EntitiesODS(CRMWrapperBase w,EntityInternalItems f,AttributeInternalRequiredLevel reqLevel,bool isAdm)
        {            
			_wrapper			=	w;
			_isAdmin			=	isAdm;
			_entityFlags		=	f;
			_requiredLevel		=	reqLevel;
            // Add all entities in the system to the array
            AddEntitiesToDataSet();
            
        }
		public EntitiesODS(CRMWrapperBase w,EntityInternalItems f,bool isAdm)
        {            
			_wrapper			=	w;
			_isAdmin			=	isAdm;
			_entityFlags		=	f;
            // Add all entities in the system to the array
            AddEntitiesToDataSet();
            
        }
		public EntitiesODS(CRMWrapperBase w,bool isAdm)
        {            
			_wrapper			=	w;
			_isAdmin			=	isAdm;

            // Add all entities in the system to the array
            AddEntitiesToDataSet();
            
        }

		public EntitiesODS(CRMWrapperBase w)
        {            
			_wrapper			=	w;
			_isAdmin			=	true;
            // Add all entities in the system to the array
            AddEntitiesToDataSet();
            
        }
        
        /// <summary>
        /// This adds all entities in the system (supported and custom)
        /// </summary>
        private void AddEntitiesToDataSet()
        {
            wrapper.IterateMetaEntities(entityFlags,isAdmin,false,delegate(string s,string dn){AddEntityToDataSet(s);});
        }

        /// <summary>
        /// Adds the specified entity to the list with the proper display name
        /// </summary>
        /// <param name="entityName">Schema name of entity being added</param> 
        private void AddEntityToDataSet(string entityName)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS AddEntityToDataSet entityName: {0}.",entityName),CRMTraceSwitch.Sw.Info);
            // Retrieve entity
            EntityConfig entity = new EntityConfig(wrapper,entityName, entityFlags,requiredLevel,isAdmin);
			entity.InsertDataSet(EntitiesDs,false,false,false,false,false);
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS AddEntityToDataSet entityName: {0} Added.",entityName),CRMTraceSwitch.Sw.Info);
        }
		
		// Select all entities.
		public DataTable GetAllEntities(string sortColumns, int startRecord, int maxRecords)
		{
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS GetAllEntities sortColumns: {0}, startRecord: {1}, maxRecords: {2}",sortColumns,startRecord,maxRecords),CRMTraceSwitch.Sw.Info);
			VerifySortColumns(sortColumns);
			return EntitiesDs.Tables["Entities"];
		}

		public bool GetEntityName(int typeCode,ref string entityName,ref string entityDisplayName)
		{
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS GetEntityByTypeCode typeCode: {0}",typeCode),CRMTraceSwitch.Sw.Info);
			DataTable tb	= EntitiesDs.Tables["Entities"];
			for (int i = 0; i < tb.Rows.Count; i++)
			{
				DataRow rw	=	tb.Rows[i];
				if ((int)rw["typeCode"] == typeCode)
				{
					entityDisplayName	=	(string)rw["displayName"];
					entityName			=	 (string)rw["schemaName"];
					return true;
				}
			}
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS GetEntityByTypeCode typeCode not found: {0}",typeCode),CRMTraceSwitch.Sw.Info);
			return false;
		}

		public int SelectCount()
		{
			int cnt	=	EntitiesDs.Tables["Entities"].Rows.Count;
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS VerifySortColumns SelectCount: {0}.",cnt),CRMTraceSwitch.Sw.Info);
			return cnt;
		}


		//////////
		// Verify that only valid columns are specified in the sort expression to avoid a SQL Injection attack.
		private void VerifySortColumns(string sortColumns)
		{
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS VerifySortColumns sortColumns: {0}.",sortColumns),CRMTraceSwitch.Sw.Info);
			if (sortColumns.ToLowerInvariant().EndsWith(" desc"))
				sortColumns = sortColumns.Substring(0, sortColumns.Length - 5);

			string[] columnNames = sortColumns.Split(',');

			foreach (string columnName in columnNames)
			{
				switch (columnName.Trim().ToLowerInvariant())
				{
					case "displayname":
						break;
					case "schemaname":
						break;
					case "typecode":
						break;
					default:
						//throw new ArgumentException("SortColumns contains an invalid column name.");
						break;
				}
			}
		}

		// Select an entities attributes.
		public DataView GetAttributes(int typeCode)
		{
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntitiesODS GetAttributes typeCode: {0}.",typeCode),CRMTraceSwitch.Sw.Info);
			DataTable tb	=	EntitiesDs.Tables["Attributes"];
			DataView	dv	=	new DataView(tb);
			dv.RowFilter	=	string.Format("typeCode={0}",typeCode);
			return dv;
		}
	}
}
